package com.mall.untils;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

/**
 * Created by sa on 2015/4/14 14:55
 * 获得临时票据类
 */
@Service
public class TicketUtil {

    Logger logger = Logger.getLogger(TicketUtil.class);

    @Resource
    private AccessTokenService accessTokenService;


    /**
     * 获得票据的请求地址
     */
//    String url_get = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8d11eeefe31400a8&secret=35099273b48ce317f1b503f37d4f7ade";

    String url_get = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+Constants.appid+"&secret="+Constants.secret;


    String jsapi_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";

    /**
     * 上一次获得 access_token 的时间
     */
    long timeAgo = System.currentTimeMillis() / 1000;

    public long getTimeAgo() {
        return timeAgo;
    }

    public void setTimeAgo(long timeAgo) {
        this.timeAgo = timeAgo;
    }


    /**
     * 返回获得的 access_token 临时票据
     */
    String access_token;

    public String getAccess_token() {
    	String jsTicketJson = HttpGetUtil.getStringByGet("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="+this.access_token);
    	if(jsTicketJson.contains("40001")){
    		logger.info("微信getAccess_token=============过期====="+jsTicketJson);
    		return accessTokenByJson();
    	}else{
    		return access_token;
    	}
    	
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    /**
     * 返回获得的 jsApi_ticket
     */
    String jsTicket;

    public String getJsTicket() {
        return jsTicket;
    }

    public void setJsTicket(String jsTicket) {
        this.jsTicket = jsTicket;
    }

    private String getToken() {

        try {

            String str = HttpGetUtil.getStringByGet(url_get);

            //获得当前时间
            this.setTimeAgo(System.currentTimeMillis() / 1000);

            return str;

        } catch (Exception ex) {
            logger.info(ex.getMessage());
            this.timeAgo = System.currentTimeMillis() / 1000;
            return null;
        }
    }


    private String accessTokenByJson() {

        String jsonStr = getToken();

        if (jsonStr == null) {
            logger.info("获取服务器临时票据失败！！！！");
            return null;
        } else {
            JSONObject jsonObject = JSONObject.fromObject(jsonStr);
            String access_token = jsonObject.getString("access_token");
            if (access_token != null && !access_token.equals("")) {
                this.setAccess_token(access_token);

                accessTokenService.add(access_token);

                return access_token;
            } else {
                return null;
            }

        }
    }

    public String jsapiTicket() {

        String access_token2 = accessTokenByJson();

        String uriJsapi = String.format(jsapi_ticket, access_token2);

        logger.info(uriJsapi);

        String jsTicketJson = HttpGetUtil.getStringByGet(uriJsapi);

        if (jsTicketJson == null) {
            logger.info("获取服务器jsapi_ticket失败！！！！");
            return null;
        } else {
            JSONObject jsonObject = JSONObject.fromObject(jsTicketJson);
            String ticket = jsonObject.getString("ticket");
            if (ticket != null && !ticket.equals("")) {

                this.setJsTicket(ticket);
                return ticket;
            } else {
                return null;
            }

        }
    }
}